package com.css.fxfzypg.modules.maps.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.common.utils.AreaBoundaryUtil;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.modules.maps.service.QpResultsMapService;
import com.css.fxfzypg.modules.saresults.entity.DzqhApCruxLayerPfEntity;
import com.css.fxfzypg.modules.saresults.entity.DzqhQpBasicMapEntity;
import com.css.fxfzypg.modules.saresults.vo.SaResultsHlVo;
import com.css.fxfzypg.util.CreateGson;
import com.css.fxfzypg.util.PlatformObjectUtils;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import com.css.fxfzypg.zcpt.sys.service.SysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.geometry.jts.JTS;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.filter.Filter;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author zyt
 * @Date: 2022/12/23
 */
@Service
@Slf4j
public class QpResultsMapServiceImpl implements QpResultsMapService {
    @Resource
    JdbcTemplate jdbcTemplate;
    @Resource
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    SUserService sUserService;

    @Autowired
    SysAreaService sysAreaService;

    /**
     * 数据源
     * 10.19.41.111
     */
    @Value("${spring.datasource.url}")
    private String url = "";
    @Value("${spring.datasource.username}")
    private String name = "";
    @Value("${spring.datasource.password}")
    private String pwd = "";

    /**
     * 获取数据库连接
     * SQL语句
     */
    private Connection getConnection() throws Exception {
        //Class.forName("com.mysql.cj.jdbc.Driver");
        Class.forName("org.postgresql.Driver");
        Connection conn = DriverManager.getConnection(url, name, pwd);
        return conn;
    }

    //校验shp文件
    public String checkSHPFiles(String filePath, String projectId) {
        try {
            String returnMsg = "";
            System.out.println(new Date()+"-------------------1.开始readSHPFile");
            System.out.println(new Date()+"-------------------2.开始校验");
            //校验是否为2000坐标系
            if (!(checkCGCS2000(filePath))){
                System.out.println(new Date()+"-----------校验失败.请上传正确的CGCS2000坐标系数据及.prj文件.");
                return "checkNotCGCS2000";
            }
            String cpgPath = filePath.substring(0, filePath.length() - 4) + ".cpg";
            String codeType = readCPG(cpgPath);//读取cpg文件编码
            //读取shp文件并校验--type上传类型（区评成果_）
            List<Object> list = readSHPFileCheck(filePath, codeType,"区评成果_");
            codeType = (String) list.get(0);//编码类型（0：UTF-8，1：GBK）
            int dataLength = (int) list.get(1);//数据长度
            String checkResult = (String) list.get(2);//校验结果
            String geomText = (String) list.get(3);//1条空间数据
            //编码类型（0：UTF-8，1：GBK）
            /* if (codeType.equals("UTF-8")) {
                codeType = "0";
            }else{
                codeType = "1";
            }*/
            System.out.println(new Date()+"-------------------3.结束readSHPFile");
            System.out.println(new Date()+"-----------4.结束校验");
            if(checkResult.equals("校验成功")){
                System.out.println(new Date()+"-------------------1.完成校验GeometryIsNotEqualsCoordinate");
                System.out.println(new Date()+"-------------------2.完成校验是否有乱码");
                System.out.println(new Date()+"-------------------3.完成校验字段空值");
                //System.out.println(new Date()+"-------------------4.完成校验是否为罗马数字");
                System.out.println(new Date()+"-----------校验成功.");
                String fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length() - 4);
                //获取经纬度字符串
                //解析空间数据经纬度字符串
                List<String> lonlatStrList = getLonLatStringByGeomText(geomText);
                String longitude = lonlatStrList.get(0);
                String latitude = lonlatStrList.get(1);
                //已有项目ID
                if (!PlatformObjectUtils.isEmpty(projectId)) {
                    //更新空间数据wkt
                    updateGeomText(fileName+".shp", geomText, longitude, latitude, projectId);
                }
                returnMsg = "导入成功"+fileName+".shp;空间数据"+geomText+"经度"+longitude+"纬度"+latitude;
            }else{
                System.out.println(new Date()+"-----------校验失败."+checkResult);
                returnMsg = checkResult;
            }
            //返回的消息
            return returnMsg;
        } catch (RuntimeException e) {
            log.error(e.getMessage(), e);
            return "插入或更新数据出现错误: <br/>" + e.getMessage();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "数据导入失败, 服务器内部出现异常!";
        }
    }

    //区评更新空间数据wkt
    @Override
    public void updateGeomText(String fileName, String geomText, String longitude, String latitude, String projectId) {
        String sql = "update dzqh_qp_basic_map set cp_file=?,geom_text=?,longitude=?,latitude=? " +
                "where project_id=?";
        jdbcTemplate.update(sql, fileName, geomText, longitude, latitude, projectId);
    }

    //解析空间数据经纬度字符串，保留6位小数
    public List<String> getLonLatStringByGeomText(String geomText){
        List<String> lonlatStrList = new ArrayList<String>();
        String lonString = "";//经度
        String latString = "";//纬度
        if (!PlatformObjectUtils.isEmpty(geomText)) {
            geomText = geomText.toUpperCase();//转为大写字母
            if(geomText.indexOf("MULTIPOLYGON")!=-1){
                geomText = geomText.substring(geomText.indexOf("(((") + 3, geomText.lastIndexOf(")))"));
                geomText = geomText.replace(")), ((", "|");
                //geomText = geomText.replace("), (", "#");
                geomText = geomText.replace("), (", "|");
                String[] coordinates = StringUtils.split(geomText, "|");
                for (int i = 0; i < coordinates.length; i++) {
                    String[] coords = coordinates[i].split(", ");
                    for (int j = 0; j < coords.length; j++) {
                        String[] lonlat = coords[j].split(" ");
                        //获取四舍五入保留6位小数的字符串
                        String lon = getDecimalFormat(lonlat[0]);
                        String lat = getDecimalFormat(lonlat[1]);
                        //经纬度
                        lonString += lon + ",";
                        latString += lat + ",";
                    }
                }

            }else if(geomText.indexOf("POLYGON")!=-1 || geomText.indexOf("MULTILINESTRING")!=-1){
                geomText = geomText.substring(geomText.indexOf("((") + 2, geomText.lastIndexOf("))"));
                geomText = geomText.replace("), (", "|");
                String[] coordinates = StringUtils.split(geomText, "|");
                for (int i = 0; i < coordinates.length; i++) {
                    String[] coords = coordinates[i].split(", ");
                    for (int j = 0; j < coords.length; j++) {
                        String[] lonlat = coords[j].split(" ");
                        //获取四舍五入保留6位小数的字符串
                        String lon = getDecimalFormat(lonlat[0]);
                        String lat = getDecimalFormat(lonlat[1]);
                        //经纬度
                        lonString += lon + ",";
                        latString += lat + ",";
                    }
                }
            }else if(geomText.indexOf("LINESTRING")!=-1 || geomText.indexOf("POINT")!=-1){
                geomText = geomText.substring(geomText.indexOf("(") + 1, geomText.lastIndexOf(")"));
                String[] coords = geomText.split(", ");
                for (int j = 0; j < coords.length; j++) {
                    String[] lonlat = coords[j].split(" ");
                    //获取四舍五入保留6位小数的字符串
                    String lon = getDecimalFormat(lonlat[0]);
                    String lat = getDecimalFormat(lonlat[1]);
                    //经纬度
                    lonString += lon + ",";
                    latString += lat + ",";
                }
            }
            //经纬度处理--去除最后的,
            if (!PlatformObjectUtils.isEmpty(lonString) && !PlatformObjectUtils.isEmpty(latString)) {
                lonString = lonString.substring(0, lonString.length() - 1);
                latString = latString.substring(0, latString.length() - 1);
            }
        }

        lonlatStrList.add(lonString);
        lonlatStrList.add(latString);

        return lonlatStrList;
    }

    //获取四舍五入保留6位小数的字符串
    public String getDecimalFormat(String numStr){
        double num = Double.parseDouble(numStr);
        BigDecimal b = new BigDecimal(num);
        double format = b.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
        String formatStr = String.valueOf(format);

        return formatStr;
    }

    //根据经纬度获取geom_text字段值
    @Override
    public String getGeomTextByLonLatString(String[] longitude, String[] latitude){
        String geomText = "";
        if(longitude!=null && latitude!=null && longitude.length>0 && longitude.length==latitude.length){
            if(longitude.length==1){//点
                if (!PlatformObjectUtils.isEmpty(longitude[0]) && !PlatformObjectUtils.isEmpty(latitude[0])) {
                    geomText = "POINT ("+longitude[0]+" "+latitude[0]+")";
                }
            }else{
                if(longitude.length>=4){//线或面
                    int lastIndex = longitude.length - 1;
                    if(!PlatformObjectUtils.isEmpty(longitude[0]) && !PlatformObjectUtils.isEmpty(latitude[0]) &&
                            longitude[0]==longitude[lastIndex] && latitude[0]==latitude[lastIndex]){//面
                        geomText += "MULTIPOLYGON (((";
                        for(int i=0;i<longitude.length;i++){
                            String lon = longitude[i];
                            String lat = latitude[i];
                            if(i>0){
                                geomText += ", ";
                            }
                            geomText += lon+" "+lat;
                        }
                        geomText += ")))";
                    }else{//线
                        geomText += "MULTILINESTRING ((";
                        for(int i=0;i<longitude.length;i++){
                            String lon = longitude[i];
                            String lat = latitude[i];
                            if(i>0){
                                geomText += ", ";
                            }
                            geomText += lon+" "+lat;
                        }
                        geomText += "))";
                    }
                }else{//线
                    geomText += "MULTILINESTRING ((";
                    for(int i=0;i<longitude.length;i++){
                        String lon = longitude[i];
                        String lat = latitude[i];
                        if(i>0){
                            geomText += ", ";
                        }
                        geomText += lon+" "+lat;
                    }
                    geomText += "))";
                }
            }
        }

        return geomText;
    }

    //区评成果目录项目信息地图圈选查询
    @Override
    public HashMap<String, Object> queryQpResultsProjectByGeomText(DzqhQpBasicMapEntity qpBasicMapEntity, String geomText) {
        String userId = PlatformSessionContext.getUserID();
        String role = sysRoleService.getRoleByUserId(userId);
        String user = sUserService.getSUser(PlatformSessionContext.getUserID());
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        //单位id
        String orgId = sUser.getOrgId();
        //省级id
        String provinceId = sUser.getProvinceId();
        List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
        ArrayList<String> roleList = new ArrayList<>();
        for (Map roleMap : roleMaps) {
            String roleCode = (String) roleMap.get("roleCode");
            roleList.add(roleCode);
        }
        if (roleList.contains(FxfzConstants.DZQH_GL_ROLE)) {
            //系统管理员
            qpBasicMapEntity.setRole("0");
        } else if (roleList.contains(FxfzConstants.DZQH_PRI_GL_ROLE)) {
            //省级管理员
            qpBasicMapEntity.setRole("1");
        } else if (roleList.contains(FxfzConstants.DZQH_GAME_GL_ROLE)) {
            //局级管理员
            qpBasicMapEntity.setRole("2");
        } else {
            //普通用户
            qpBasicMapEntity.setRole("3");
        }
        StringBuilder sql = new StringBuilder("select * from dzqh_qp_basic_map where sub_status='1' and update_status='0'");
        if (qpBasicMapEntity.getRole().equals("3")){
            sql.append(" and is_delete='0' and create_user='"+userId+"'");
        }
        if (qpBasicMapEntity.getRole().equals("1")){
            sql.append(" and province_id='"+provinceId+"'");
        }
        if (qpBasicMapEntity.getRole().equals("2")){
            sql.append(" and (province_id='"+provinceId+"' or org_id='"+orgId+"')");
        }

        if (!PlatformObjectUtils.isEmpty(qpBasicMapEntity.getProjectName())) {
            sql.append(" and project_name like '%" + qpBasicMapEntity.getProjectName() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(qpBasicMapEntity.getLongitude())) {
            sql.append(" and longitude >= '"+qpBasicMapEntity.getLongitude()+"'");
        }
        if(!PlatformObjectUtils.isEmpty(qpBasicMapEntity.getEndLongitude())){
            sql.append(" and longitude <= '"+qpBasicMapEntity.getEndLongitude()+"'");
        }
        if (!PlatformObjectUtils.isEmpty(qpBasicMapEntity.getLatitude())) {
            sql.append(" and latitude >= '"+qpBasicMapEntity.getLatitude()+"'");
        }
        if(!PlatformObjectUtils.isEmpty(qpBasicMapEntity.getEndLatitude())){
            sql.append(" and latitude <= '"+qpBasicMapEntity.getEndLatitude()+"'");
        }
        if (!PlatformObjectUtils.isEmpty(qpBasicMapEntity.getApprovalStatus())) {
            sql.append(" and approval_status ='" + qpBasicMapEntity.getApprovalStatus()+"'");
        }
        if (!PlatformObjectUtils.isEmpty(qpBasicMapEntity.getReviewUnit())) {
            sql.append(" and review_unit like '%" + qpBasicMapEntity.getReviewUnit() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(qpBasicMapEntity.getStatus())) {
            sql.append(" and status = '" + qpBasicMapEntity.getStatus()+"'");
        }
        if (!PlatformObjectUtils.isEmpty(qpBasicMapEntity.getAdministrativeRegion())) {
            sql.append(" and administrative_region= '" + qpBasicMapEntity.getAdministrativeRegion()+"'");
        }
        if (!PlatformObjectUtils.isEmpty(qpBasicMapEntity.getUndertaker())) {
            sql.append(" and undertaker like '%" + qpBasicMapEntity.getUndertaker() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(qpBasicMapEntity.getRegistrant())) {
            sql.append(" and registrant like '%"+qpBasicMapEntity.getRegistrant()+"%'");
        }
        if (!PlatformObjectUtils.isEmpty(qpBasicMapEntity.getRegistrationUnit())) {
            sql.append(" and registration_unit like '% " + qpBasicMapEntity.getRegistrationUnit() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(qpBasicMapEntity.getCreateStartTime())) {
            sql.append(" and date(create_time) >= '"+qpBasicMapEntity.getCreateStartTime()+"'");
        }
        if(!PlatformObjectUtils.isEmpty(qpBasicMapEntity.getCreateEndTime())){
            sql.append(" and date(create_time) <= '"+qpBasicMapEntity.getCreateEndTime()+"'");
        }
        if (!PlatformObjectUtils.isEmpty(qpBasicMapEntity.getSubStartTime()) && !PlatformObjectUtils.isEmpty(qpBasicMapEntity.getSubEndTime())) {
            sql.append(" and sub_date >= '" + qpBasicMapEntity.getSubStartTime() + "' and sub_date <='" + qpBasicMapEntity.getSubEndTime()+"'");
        }

        //地图圈选范围查询
        if (!PlatformObjectUtils.isEmpty(geomText)) {
            //项目位置上传文件空间位置相交
            sql.append(" and geom_text is not null and geom_text!='' and ST_Intersects(st_geometryfromtext(geom_text,4490),st_geometryfromtext('"+geomText+"',4490))");
            //项目位置经纬度相交查询
            //sql.append(" and ST_Intersects(st_geometryfromtext('POINT(' || longitude || ' ' || latitude || ')',4490),st_geometryfromtext('"+geomText+"',4490))");
        }
        StringBuilder orderSql = new StringBuilder(" order by create_time desc");
        Integer total = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(DzqhQpBasicMapEntity.class)).size();
        sql.append(orderSql);
        List<DzqhQpBasicMapEntity> qpBasicMapEntityList = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(DzqhQpBasicMapEntity.class));
        for (DzqhQpBasicMapEntity qpBasicMap : qpBasicMapEntityList) {
            String region = qpBasicMap.getAdministrativeRegion();
            qpBasicMap.setAdministrativeRegion(sysAreaService.getAreaNameByAreaId(region));
        }
        HashMap<String, Object> resultMap = new HashMap();
        resultMap.put("total", total);
        resultMap.put("rows", qpBasicMapEntityList);
        return resultMap;
    }

    //区评成果目录孔位信息地图圈选查询
    @Override
    public HashMap<String, Object> queryQpResultsHlByGeomText(SaResultsHlVo saResultsHlVo, String geomText) {
        String userId = PlatformSessionContext.getUserID();
        String role = sysRoleService.getRoleByUserId(userId);
        String user = sUserService.getSUser(PlatformSessionContext.getUserID());
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        //单位id
        String orgId = sUser.getOrgId();
        //省级id
        String provinceId = sUser.getProvinceId();
        List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
        for (Map roleMap : roleMaps) {
            String roleCode = (String) roleMap.get("roleCode");
            if (roleCode.equals(FxfzConstants.DZQH_GL_ROLE)) {
                //系统管理员
                saResultsHlVo.setRole("0");
            } else if(roleCode.equals(FxfzConstants.DZQH_PRI_GL_ROLE)){
                //省级管理员
                saResultsHlVo.setRole("1");
            }else if (roleCode.equals(FxfzConstants.DZQH_GAME_GL_ROLE)){
                //局级管理员
                saResultsHlVo.setRole("2");
            }else {
                //普通用户
                saResultsHlVo.setRole("3");
            }
        }
        //区评项目信息查询
        /*StringBuilder sql = new StringBuilder("select dqm.* from dzqh_qp_basic_map dqm left join dzqh_ap_crux_layer_pf daclp on daclp.project_id = dqm.project_id " +
                "left join dzqh_ap_crux_sd dacsd on dacsd.project_id=dqm.project_id left join dzqh_ap_crux_sc dacsc on dacsc.project_id=dqm.project_id left join dzqh_ap_crux_sd dacs on dacs.project_id= dqm.project_id where dqm.sub_status='1' and dqm.update_status='0'");*/
        //区评孔位信息查询
        StringBuilder sql = new StringBuilder("select daclp.* from dzqh_qp_basic_map dqm left join dzqh_ap_crux_layer_pf daclp on daclp.project_id = dqm.project_id " +
                //"left join dzqh_ap_crux_sd dacsd on dacsd.project_id=dqm.project_id left join dzqh_ap_crux_sc dacsc on dacsc.project_id=dqm.project_id left join dzqh_ap_crux_sd dacs on dacs.project_id= dqm.project_id " +
                "where dqm.sub_status='1' and dqm.update_status='0'");
        if (saResultsHlVo.getRole().equals("3")){
            sql.append(" and dqm.is_delete='0' and dqm.create_user='"+userId+"'");
        }
        if (saResultsHlVo.getRole().equals("1")){
            sql.append(" and dqm.province_id='"+provinceId+"'");
        }
        if (saResultsHlVo.getRole().equals("2")){
            sql.append(" and (dqm.province_id='"+provinceId+"' or dqm.org_id='"+orgId+"')");
        }

        /*if (!PlatformObjectUtils.isEmpty(saResultsHlVo.getProjectName())) {
            sql.append(" and dqm.project_name like '%" + saResultsHlVo.getProjectName()+"%'");
        }
        if (!PlatformObjectUtils.isEmpty(saResultsHlVo.getHlLongitude()) && !PlatformObjectUtils.isEmpty(saResultsHlVo.getEndHlLongitude())) {
            sql.append(" and daclp.hl_longitude between '"+saResultsHlVo.getHlLongitude()+"' and '"+saResultsHlVo.getEndHlLongitude()+"'");
        }
        if (!PlatformObjectUtils.isEmpty(saResultsHlVo.getHlLatitude()) && !PlatformObjectUtils.isEmpty(saResultsHlVo.getEndHlLatitude())) {
            sql.append(" and daclp.hl_latitude between '"+saResultsHlVo.getHlLatitude()+"' and '"+saResultsHlVo.getEndHlLatitude()+"'");
        }
        if (!PlatformObjectUtils.isEmpty(saResultsHlVo.getBdosSample())) {
            sql.append(" and dacsd.bdos_sample = '" + saResultsHlVo.getBdosSample()+"'");
        }
        if (!PlatformObjectUtils.isEmpty(saResultsHlVo.getApprovalStatus())) {
            sql.append(" and dqm.approval_status ='" + saResultsHlVo.getApprovalStatus()+"'");
        }
        if (!PlatformObjectUtils.isEmpty(saResultsHlVo.getStatus())) {
            sql.append(" and dqm.status = '" + saResultsHlVo.getStatus()+"'");
        }
        if (!PlatformObjectUtils.isEmpty(saResultsHlVo.getLongitude()) && !PlatformObjectUtils.isEmpty(saResultsHlVo.getEndLongitude())) {
            sql.append(" and dqm.longitude between '"+saResultsHlVo.getLongitude()+"' and '"+saResultsHlVo.getEndLongitude()+"'");
        }
        if (!PlatformObjectUtils.isEmpty(saResultsHlVo.getLatitude()) && !PlatformObjectUtils.isEmpty(saResultsHlVo.getEndLatitude())) {
            sql.append(" and dqm.latitude between '"+saResultsHlVo.getLatitude()+"' and '"+saResultsHlVo.getEndLatitude()+"'");
        }
        if (!PlatformObjectUtils.isEmpty(saResultsHlVo.getGeotechnicalName())) {
            sql.append(" and dacs.geotechnical_name like '%" + saResultsHlVo.getGeotechnicalName()+"%'");
        }
        if (!PlatformObjectUtils.isEmpty(saResultsHlVo.getFieldType())) {
            sql.append(" and dacsc.field_type = '" + saResultsHlVo.getFieldType()+"'");
        }*/

        //有孔位信息
        sql.append(" and daclp.project_id is not null and daclp.hl_longitude is not null and daclp.hl_latitude is not null");
        //地图圈选范围查询
        if (!PlatformObjectUtils.isEmpty(geomText)) {
            //项目信息相交
            //sql.append(" and dqm.geom_text is not null and dqm.geom_text!='' and ST_Intersects(st_geometryfromtext(dqm.geom_text,4490),st_geometryfromtext('"+geomText+"',4490))");
            //孔位信息相交
            sql.append(" and ST_Intersects(st_geometryfromtext('POINT(' || daclp.hl_longitude || ' ' || daclp.hl_latitude || ')',4490),st_geometryfromtext('"+geomText+"',4490))");
        }
        //区评项目信息
        /*StringBuilder orderSql = new StringBuilder(" group by dqm.project_id order by dqm.create_time desc");
        sql.append(orderSql);
        Integer total = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(DzqhQpBasicMapEntity.class)).size();
        List<DzqhQpBasicMapEntity> qpBasicMapEntityList = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(DzqhQpBasicMapEntity.class));
        for (DzqhQpBasicMapEntity qpBasicMap : qpBasicMapEntityList) {
            String region = qpBasicMap.getAdministrativeRegion();
            qpBasicMap.setAdministrativeRegion(sysAreaService.getAreaNameByAreaId(region));
        }
        HashMap<String, Object> resultMap = new HashMap();
        resultMap.put("total", total);
        resultMap.put("rows", qpBasicMapEntityList);*/
        //区评孔位信息
        StringBuilder orderSql = new StringBuilder(" order by daclp.project_id,daclp.create_time desc");
        sql.append(orderSql);
        Integer total = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(DzqhApCruxLayerPfEntity.class)).size();
        List<DzqhApCruxLayerPfEntity> cruxLayerPfList = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(DzqhApCruxLayerPfEntity.class));
        HashMap<String, Object> resultMap = new HashMap();
        resultMap.put("total", total);
        resultMap.put("rows", cruxLayerPfList);

        return resultMap;
    }

    //校验是否为2000坐标系
    public boolean checkCGCS2000(String path) {
        String prjPath = path.substring(0, path.length() - 4) + ".prj";
        String strWKTMercator = readPRJ(prjPath);
        if (strWKTMercator == "") return false;
        CoordinateReferenceSystem sourceTarget = null;
        try {
            sourceTarget = CRS.parseWKT(strWKTMercator);
        } catch (FactoryException e) {
            e.printStackTrace();
            System.out.println(path + ": 解析错误!");
        }
        String name = sourceTarget.getName().toString();
        if (name.indexOf("CGCS2000") != -1 || name.indexOf("cgcs2000") != -1 || name.indexOf("Geodetic_Coordinate_System_2000") != -1 ||
                name.indexOf("Geodetic Coordinate System 2000") != -1) return true;
        return false;
    }

    //读取shp文件并校验--type上传类型（区评成果_）
    public List<Object> readSHPFileCheck(String path, String codeType,String type) {
        List<Object> result = new ArrayList<Object>();
        String prjPath = path.substring(0, path.length() - 4) + ".prj";
        String strWKTMercator = readPRJ(prjPath);
        if (strWKTMercator != "") setStrWKTMercator(strWKTMercator);
        String lonLatStr = "", wkt = "";
        SimpleFeatureCollection colls1 = readShp(path, null, codeType);
        SimpleFeatureIterator iters = colls1.features();
        String resMsg = "校验成功";
        String geom = null;//读取1条空间数据
        int count = 0;
        //校验空间分辨率不是6秒
        double lon = 0, lat = 0;
        //List<String> allWktStrList = new ArrayList<String>();//全部空间信息字符串列表
        List<Double> allLonList = new ArrayList<Double>();
        List<Double> allLatList = new ArrayList<Double>();
        SimpleFeature sf = null;

        //校验矢量面是否在省市县所在区域内
        List<List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon>> multiPolygonList = new ArrayList<List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon>>();
        List<Geometry> multiPolygonGeometryList = new ArrayList<Geometry>();

        while (iters.hasNext()) {
            if(count%100000==0){
                System.out.println(count);
            }
            sf = iters.next();
            List<Object> attributes = sf.getAttributes();
            //0.判断字段数量是否符合要求
            int size = attributes.size();
            if("区评成果_".equals(type)){
                if(size<1){
                    resMsg = "fieldNumError";
                    break;
                }
            }
            //校验矢量面是否在省市县所在区域内
            /*if("RLMPolygon_".equals(type)){
                //根据属性获取矢量面列表
                List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> polygonList = getPolygonList(attributes);
                //校验数据是否在省市县所在区域边界内
                if(!newCheckPointIsInDistrict(boundaries, polygonList)){
                    resMsg = "PointIsNotInDistrict";
                    break;
                }

                //添加到面经纬度列表用于校验面是否相交
                multiPolygonList.add(polygonList);
                //test
                Geometry polygon = getPolygonGeometryList(attributes.get(0).toString());
                multiPolygonGeometryList.add(polygon);
            }*/
            if("区评成果_".equals(type)){
                //1.校验GeometryIsNotEqualsCoordinate
                String pointWkt = attributes.get(0).toString();
                /*String A = attributes.get(1).toString();//经度
                String B = attributes.get(2).toString();//纬度
                //新校验经纬度方法
                if (!newGeometryIsEqualsCoordinate(pointWkt, A, B)) {
                    resMsg = "GeometryIsNotEqualsCoordinate";
                    break;
                }*/

                /*//可注释判断以下判断点是否在行政区划内代码
                //判断点是否在行政区划内
                if(!newCheckPointIsInDistrictBoundary(boundaries,A,B)){
                    resMsg = "PointIsNotInDistrict";
                    break;
                }*/
            }
            //2.校验是否有乱码
            int msssyIndex = -1;
            //校验是否有乱码
            for (int j = 0; j < attributes.size(); j++) {
                String value = attributes.get(j).toString();
                for (int k = 0; k < value.length() / 2; k++) {
                    char c = value.charAt(k);
                    // 当从Unicode编码向某个字符集转换时，如果在该字符集中没有对应的编码，则得到0x3f（即问号字符?）
                    //从其他字符集向Unicode编码转换时，如果这个二进制数在该字符集中没有标识任何的字符，则得到的结果是0xfffd
                    if ((int) c == 0xfffd) {
                        // 存在乱码
                        msssyIndex = count;
                        break;
                    }
                }
                if(msssyIndex!=-1){
                    resMsg = "messyCode#"+msssyIndex;
                    break;
                }
            }
            if(msssyIndex!=-1){
                break;
            }
            //3.校验字段空值
            for (int j = 0; j < attributes.size(); j++) {
                String value = attributes.get(j).toString();
                //校验字段空值
                if (value == null || "".equals(value.trim())){
                    resMsg = "fieldNullValue";
                    break;
                }
            }
            if(!resMsg.equals("校验成功")){
                break;
            }
            //上传类型（区评成果_）
            /*if ("区评成果_".equals(type)) {
                //4.校验空间分辨率不是6秒
                String A = attributes.get(1).toString();
                String B = attributes.get(2).toString();
                lon = Double.parseDouble(A);
                lat = Double.parseDouble(B);
                allLonList.add(lon);
                allLatList.add(lat);
                //校验是否空间位置重叠
                //allWktStrList.add(attributes.get(0).toString());
            }*/

            //4.校验数据内容是否符合规范
            if ("区评成果_".equals(type)) {
                //
            }

            count++;
            //只读取1条数据
            //空间数据
            geom = attributes.get(0).toString();
            break;
        }
        iters.close();
        System.out.println(count);
        //上传类型（区评成果_）
        /*if ("区评成果_".equals(type) && resMsg.equals("校验成功")) {
            //校验空间分辨率不是6秒
            if (!(isLessSixSecondDistance(allLonList,allLatList))){
                resMsg = "SpatialResolutionError";
            }
        }*/
        //校验矢量面是否在存在两两相交（或自相交）
        /*if("RLMPolygon_".equals(type) && resMsg.equals("校验成功")){
            //校验矢量面是否在存在自相交
            String resultStr = checkIsPolygonsIntersect(multiPolygonList);
            if(resultStr!="校验成功"){
                resMsg = resultStr;
            }
            if(resMsg.equals("校验成功")){
                //校验矢量面是否在存在两两相交
                resultStr = checkIsPolygonGeometrysIntersect(multiPolygonGeometryList);
                if(resultStr!="校验成功"){
                    resMsg = resultStr;
                }
            }
        }*/
        //返回结果
        result.add(codeType);//编码类型（0：UTF-8，1：GBK）
        result.add(count);//数据长度
        result.add(resMsg);//校验结果
        result.add(geom);//1条空间数据
        //校验是否有乱码
        if(resMsg.indexOf("messyCode")!=-1 && !codeType.equals("GBK")){
            result = readSHPFileCheck(path, "GBK",type);
        }

        return result;
    }

    //读取cpg文件编码
    public String readCPG(String path) {
        String codeType = "UTF-8";
        StringBuffer result = new StringBuffer();
        File file = new File(path);
        if (!file.exists()) return "";
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                result.append(tempString);
            }
            reader.close();
            //返回结果
            codeType = result.toString();
            codeType = codeType.toUpperCase();//转换大写
        } catch (IOException e) {
            e.printStackTrace();
        }
        return codeType;
    }

    public String readPRJ(String path) {
        StringBuffer result = new StringBuffer();
        File file = new File(path);
        if (!file.exists()) return "";
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                result.append(tempString);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    public SimpleFeatureCollection readShp(String path, Filter filter, String codeType) {
        SimpleFeatureSource featureSource = readStoreByShp(path, codeType);
        if (featureSource == null) return null;
        try {
            return filter != null ? featureSource.getFeatures(filter) : featureSource.getFeatures();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public SimpleFeatureSource readStoreByShp(String path, String codeType) {
        File file = new File(path);
        FileDataStore store;
        SimpleFeatureSource featureSource = null;
        try {
            store = FileDataStoreFinder.getDataStore(file);
            ((ShapefileDataStore) store).setCharset(Charset.forName(codeType));
            featureSource = store.getFeatureSource();
            store.dispose();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return featureSource;
    }

    //获取省市县所在区域边界列表
    public List<com.css.fxfzypg.modules.spatialData.repository.entity.Point[]> getDistrictBoundaryByString(String coordinate){
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Point[]> boundaries = new ArrayList<>();
        if (coordinate == null || "".equals(coordinate)) {
            System.out.println("NoDistrictBoundaryData");
        } else {
            coordinate = coordinate.substring(coordinate.indexOf("(((") + 3, coordinate.lastIndexOf(")))"));
            coordinate = coordinate.replace(")), ((", "|");
            //coordinate = coordinate.replace("), (", "#");
            coordinate = coordinate.replace("), (", "|");
            String[] coordinates = StringUtils.split(coordinate, "|");
            for (int j = 0; j < coordinates.length; j++) {
                coordinates[j] = coordinates[j].replace(", ",";");
                coordinates[j] = coordinates[j].replace(" ",",");
                String[] lonlats = StringUtils.split(coordinates[j],";");
                com.css.fxfzypg.modules.spatialData.repository.entity.Point[] points = new com.css.fxfzypg.modules.spatialData.repository.entity.Point[lonlats.length];
                for (int i = 0;i < lonlats.length;i++) {
                    String[] lonlat = StringUtils.split(lonlats[i], ",");
                    com.css.fxfzypg.modules.spatialData.repository.entity.Point point = new com.css.fxfzypg.modules.spatialData.repository.entity.Point();
                    point.x = Double.parseDouble(lonlat[0]);
                    point.y = Double.parseDouble(lonlat[1]);
                    points[i] = point;
                }
                boundaries.add(points);
            }
        }

        return boundaries;
    }

    public String reverseWktMultiPolygon(String wktPolygon) {
        String oldWkt = wktPolygon;
        oldWkt = oldWkt.substring(oldWkt.indexOf("(((") + 3, oldWkt.lastIndexOf(")))"));
        oldWkt = oldWkt.replace(")), ((", "|");
        oldWkt = oldWkt.replace("), (", "#");

        String wktPolygon1 = "";
        String[] polygon1 = StringUtils.split (oldWkt, "|");
        for (int i = 0; i < polygon1.length; i++) {
            if(polygon1[i].indexOf("#")!=-1){
                String[] polygon2 = StringUtils.split(polygon1[i], "#");
                for (int j = 0; j < polygon2.length; j++) {
                    String wktPolygon2 = "";
                    String[] coords = polygon2[j].split(", ");
                    for (int k = 0; k < coords.length; k++) {
                        String[] lonLat = coords[k].split(" ");
                        String lon = lonLat[1];
                        String lat = lonLat[0];
                        wktPolygon2 += lon + " " + lat + ", ";
                    }
                    wktPolygon1 += wktPolygon2.substring(0, wktPolygon2.length() - 2) + "), (";
                }
                wktPolygon1 = wktPolygon1.substring(0, wktPolygon1.length() - 4) + ")), ((";
            }else{
                String wktPolygon2 = "";
                String[] coords = polygon1[i].split(", ");
                for (int k = 0; k < coords.length; k++) {
                    String[] lonLat = coords[k].split(" ");
                    String lon = lonLat[1];
                    String lat = lonLat[0];
                    wktPolygon2 += lon + " " + lat + ", ";
                }
                wktPolygon1 += wktPolygon2.substring(0, wktPolygon2.length() - 2) + ")), ((";
            }
        }
        wktPolygon1 = wktPolygon1.substring(0, wktPolygon1.length() - 6);

        return "MULTIPOLYGON (((" + wktPolygon1 + ")))";
    }

    public String reverseWktPolygon(String wktPolygon) {
        String oldWkt = wktPolygon;
        oldWkt = oldWkt.substring(oldWkt.indexOf("(") + 2, oldWkt.lastIndexOf("))"));

        String polygonWkt = "Polygon (", coordinate = "";
        String sp = oldWkt.indexOf("),(") != -1 ? "),(" : (oldWkt.indexOf("), (") != -1 ? "), (" : "");
        if ("".equals(sp)) {
            coordinate = "(";
            String[] coordinates = oldWkt.split(",");
            for (int i = 0; i < coordinates.length; i++) {
                String[] coords = coordinates[i].split(" ");
                coordinate += coords[1] + " " + coords[0] + ",";
            }
            coordinate = coordinate.substring(0, coordinate.length() - 1) + ")";
            polygonWkt += coordinate + ")";
        } else {
            oldWkt = oldWkt.replace(sp, "#"); sp = "#";
            String[] coordinates = oldWkt.split(sp);
            for (int i = 0; i < coordinates.length; i++) {
                coordinate = coordinates[i];
                String _coordinates = "(";
                String[] coords = coordinate.split(","), _coords = null;
                for (int j = 0; j < coords.length; j++) {
                    _coords = coords[j].split(" ");
                    _coordinates += _coords[1] + " " + _coords[0] + ",";
                }
                _coordinates = _coordinates.substring(0, _coordinates.length() - 1) + ")";
                polygonWkt += _coordinates + ",";
            }
            polygonWkt += polygonWkt.substring(0, polygonWkt.length() - 1) + ")";
        }
        return polygonWkt;
    }

    public String reverseWktPoint(String wktPoint) {
        String oldWkt = wktPoint;
        oldWkt = oldWkt.substring(oldWkt.indexOf("(") + 1, oldWkt.lastIndexOf(")"));
        String[] coords = oldWkt.split(" ");
        return "POINT (" + coords[1] + " " + coords[0] + ")";
    }

    public String reverseWktMultiPoint(String wktMultiPoint) {
        String oldWkt = wktMultiPoint;
        oldWkt = oldWkt.substring(oldWkt.indexOf("(") + 2, oldWkt.lastIndexOf(")") - 1);
        String sp = oldWkt.indexOf("),(") != -1 ? "),(" : (oldWkt.indexOf("), (") != -1 ? "), (" : "");
        String[] coordinates = StringUtils.split(oldWkt, sp);
        String newWkt = "MULTIPOINT ((", coordinate = "";
        String[] coords = null;
        for (int i = 0; i < coordinates.length; i++) {
            coordinate = coordinates[i];
            coords = coordinate.split(" ");
            //newWkt += "(" + coords[1] + " " + coords[0] + "),";
            newWkt += coords[1] + " " + coords[0] + ",";
        }
        newWkt = newWkt.substring(0, newWkt.length() - 1) + "))";
        return newWkt;
    }

    //根据属性获取boundary.Point数组列表
    public List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> getPolygonList(List<Object> attributes) {
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Point> pointArray0 = null;//面点数组
        List<List<com.css.fxfzypg.modules.spatialData.repository.entity.Point>> noPointList = null;//镂空的面点数组列表
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Point> pointArray = null;
        com.css.fxfzypg.modules.spatialData.repository.entity.Point point = null;
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> polygonList = new ArrayList<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon>();
        com.css.fxfzypg.modules.spatialData.repository.entity.Polygon polygon = null;

        String coordinates = attributes.get(0).toString();
        try{
            if (coordinates.indexOf("MULTIPOLYGON") != -1) {
                coordinates = coordinates.substring(coordinates.indexOf("(((") + 3, coordinates.lastIndexOf(")))"));
                if (coordinates.indexOf(")), ((") != -1) {//多个面
                    coordinates = coordinates.replace(")), ((", "|");
                    coordinates = coordinates.replace("), (", "#");
                    String[] geometries = StringUtils.split(coordinates, "|");
                    for (int j = 0; j < geometries.length; j++) {
                        String geometry = geometries[j];
                        //获取面
                        polygon = new com.css.fxfzypg.modules.spatialData.repository.entity.Polygon(geometry);
                        polygonList.add(polygon);
                    }

                }else if (coordinates.indexOf("), (") != -1) {//单个面（包括镂空的面）
                    coordinates = coordinates.replace("), (", "#");
                    //获取面
                    polygon = new com.css.fxfzypg.modules.spatialData.repository.entity.Polygon(coordinates);
                    polygonList.add(polygon);

                }else{//单个面
                    //获取面
                    polygon = new com.css.fxfzypg.modules.spatialData.repository.entity.Polygon(coordinates);
                    polygonList.add(polygon);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            //System.out.println("矢量面："+attributes.get(0).toString());
        }

        return polygonList;
    }
    
    //根据属性获取矢量面Geometry
    public Geometry getPolygonGeometryList(String coordinates) {
        Geometry geometry = null;
        try{
            GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
            WKTReader reader = new WKTReader(geometryFactory);
            geometry = reader.read(coordinates);
        }catch (Exception e){
            e.printStackTrace();
        }

        return geometry;
    }

    public boolean newGeometryIsEqualsCoordinate(String wkt, String lon, String lat) {
        String wktPart = "";
        if (wkt.toLowerCase().indexOf("multipoint") != -1) {
            wktPart = wkt.substring(wkt.indexOf("(") + 2, wkt.lastIndexOf(")") - 1);
        } else if (wkt.toLowerCase().indexOf("point") != -1) {
            wktPart = wkt.substring(wkt.indexOf("(") + 1, wkt.lastIndexOf(")"));
        }

        int det = 1 + 8;//保留8位小数判断
        String[] array = wktPart.split(" ");
        String longitude = array[0], latitude = array[1];
        String newWktLongitudeStr = newKeepDecimalDigits(longitude, det), newWktLatitudeStr = newKeepDecimalDigits(latitude, det);
        String newLongitudeStr = newKeepDecimalDigits(lon, det), newLatitudeStr = newKeepDecimalDigits(lat, det);

        double newWktLongitude = Double.parseDouble(newWktLongitudeStr), newWktLatitude = Double.parseDouble(newWktLatitudeStr);
        double newLongitude = Double.parseDouble(newLongitudeStr), newLatitude = Double.parseDouble(newLatitudeStr);

        //if (newWktLongitude == newLongitude && newWktLatitude == newLatitude) return true;
        //判断是否在10-6次方内
        double tempLon = Math.abs(newWktLongitude - newLongitude);
        double tempLat = Math.abs(newWktLatitude - newLatitude);
        if(tempLon<0.000001 && tempLat<0.000001){
            return true;
        }

        //判断保留8位（不四舍五入）属性字段经纬度与geometry是否一致
        if(getGeometryIsEqualsCoordinateBool(longitude, latitude, lon, lat, det)) return true;

        return false;
    }

    private String newKeepDecimalDigits(String floatStr, int det) {
        int index = floatStr.indexOf("."), len = floatStr.length();
        if (index == -1) return floatStr;
        int temp=det+1;
        String tempfloatPart=floatStr.substring(index + 1, (len > (index + temp)) ? (index + temp) : len);
        String floatPart = floatStr.substring(index + 1, (len > (index + det)) ? (index + det) : len);

        boolean bool = false;//判断是否四舍五入
        int findex=0;
        String sindex="";
        if(tempfloatPart.length()>floatPart.length()){
            if(tempfloatPart.startsWith(floatPart)&&(tempfloatPart.endsWith("9") || tempfloatPart.endsWith("8") || tempfloatPart.endsWith("7") || tempfloatPart.endsWith("6") || tempfloatPart.endsWith("5"))){
                for(int i=floatPart.length()-1;i>=0;i--){
                    String subStr = floatPart.substring(i, i+1);
                    if(subStr.equals("9")){
                        continue;
                    }
                    findex=i;
                    sindex=Integer.toString(Integer.parseInt(subStr)+1);
                    break;
                }
                floatPart= floatPart.substring(0, findex)+ sindex;
                bool = true;
            }
        }

        String newFloatStr = floatStr.substring(0, index) + "." + floatPart;
        if(bool && sindex.equals("")){//floatPart都是9
            newFloatStr = Integer.toString(Integer.parseInt(floatStr.substring(0, index))+1);
        }

        return newFloatStr;
    }

    //保留8位（不四舍五入）
    private String newKeepDecimalDigits2(String floatStr, int det) {
        int index = floatStr.indexOf("."), len = floatStr.length();
        if (index == -1) return floatStr;
        String floatPart = floatStr.substring(index + 1, (len > (index + det)) ? (index + det) : len);
        String newFloatStr = floatStr.substring(0, index) + "." + floatPart;

        return newFloatStr;
    }

    //判断保留8位（不四舍五入）属性字段经纬度与geometry是否一致
    private boolean getGeometryIsEqualsCoordinateBool(String longitude, String latitude, String lon, String lat, int det){
        boolean bool = false;
        String newWktLongitudeStr = newKeepDecimalDigits2(longitude, det), newWktLatitudeStr = newKeepDecimalDigits2(latitude, det);
        String newLongitudeStr = newKeepDecimalDigits2(lon, det), newLatitudeStr = newKeepDecimalDigits2(lat, det);

        double newWktLongitude = Double.parseDouble(newWktLongitudeStr), newWktLatitude = Double.parseDouble(newWktLatitudeStr);
        double newLongitude = Double.parseDouble(newLongitudeStr), newLatitude = Double.parseDouble(newLatitudeStr);

        //if (newWktLongitude == newLongitude && newWktLatitude == newLatitude) bool= true;
        //判断是否在10-6次方内
        double tempLon = Math.abs(newWktLongitude - newLongitude);
        double tempLat = Math.abs(newWktLatitude - newLatitude);
        if(tempLon<0.000001 && tempLat<0.000001){
            bool= true;
        }

        return bool;
    }

    //截取8位小数（不四舍五入）
    public String getNewDecimalDigits(String floatStr) {
        int det = 1 + 8;
        int index = floatStr.indexOf("."), len = floatStr.length();
        if (index == -1) return floatStr;
        String floatPart = floatStr.substring(index + 1, (len > (index + det)) ? (index + det) : len);
        String newFloatStr = floatStr.substring(0, index) + "." + floatPart;

        return newFloatStr;
    }

    //地球半径,单位 km
    private double EARTH_RADIUS = 6378.137;

    //根据经纬度，计算两点间的距离
    public double getDistance(double longitude1, double latitude1, double longitude2, double latitude2) {
        // 纬度
        double lat1 = Math.toRadians(latitude1);
        double lat2 = Math.toRadians(latitude2);
        // 经度
        double lng1 = Math.toRadians(longitude1);
        double lng2 = Math.toRadians(longitude2);
        // 纬度之差
        double a = lat1 - lat2;
        // 经度之差
        double b = lng1 - lng2;
        // 计算两点距离的公式
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(b / 2), 2)));
        // 弧长乘地球半径, 返回单位: 千米
        s =  s * EARTH_RADIUS;
        return s;
    }

    //判断6秒距离200
    public boolean isLessSixSecondDistance(List<Double> allLonList,List<Double> allLatList) {
        for(int i=0;i<allLonList.size();i++){
            if(i>100){//只判断100个点
                break;
            }
            double lng1 = allLonList.get(i);
            double lat1 = allLatList.get(i);
            boolean bool = false;
            double minDistance = -1;//最小距离
            for(int j=0;j<allLonList.size();j++){
                if(j==i){
                    continue;
                }
                double lng2 = allLonList.get(j);
                double lat2 = allLatList.get(j);
                double distance = getDistance(lng1,lat1,lng2,lat2);
                if(minDistance==-1 || distance<minDistance){
                    minDistance = distance;
                }
                if(distance<0.25){//250米
                    bool = true;
                    break;
                }
            }
            if(bool==false){
                System.out.println("第"+i+"条数据判断6秒距离不在250米内："+minDistance+"km--minDistance");
                System.out.println("第"+i+"条数据经纬度："+lng1+","+lat1);
                return false;
            }
        }

        return true;
    }

    //校验矢量面是否在存在单要素自相交
    public String checkIsPolygonsIntersect(List<List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon>> multiPolygonList) {
        String resultStr = "校验成功";
        com.css.fxfzypg.modules.spatialData.repository.entity.Polygon polygon = null;
        com.css.fxfzypg.modules.spatialData.repository.entity.Polygon polygon1 = null;
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> polygonList = null;
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> allPolygonList = null;//全部面列表
        if(multiPolygonList!=null && multiPolygonList.size()>0) {
            allPolygonList = new ArrayList<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon>();
            for (int n = 0; n < multiPolygonList.size(); n++) {
                polygonList = multiPolygonList.get(n);
                for (int i = 0; i < polygonList.size(); i++) {
                    allPolygonList.add(polygonList.get(i));
                }
            }
        }
        if(allPolygonList!=null && allPolygonList.size()>0) {
            for (int i = 0; i < allPolygonList.size(); i++) {
                polygon = allPolygonList.get(i);
                //判断矢量面是否存在自相交
                if(checkIsPolygonSelfIntersect(polygon)){
                    resultStr = "isPolygonSelfIntersect";
                    String temp = "面自相交";
                    System.out.println(temp);
                    break;
                }
            }
        }

        return resultStr;
    }

    //判断矢量面是否存在自相交
    private boolean checkIsPolygonSelfIntersect(com.css.fxfzypg.modules.spatialData.repository.entity.Polygon polygon){
        boolean bool = false;//不存在自相交
        int flag = 0;
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Point> points = polygon.points;
        for(int i = 0;i < (points.size()-1);i++){ //循环开始元素
            for(int j = i + 1;j < points.size();j++){ //循环后续所有元素
                //如果相等，则重复
                if(points.get(i).x == points.get(j).x && points.get(i).y == points.get(j).y){
                    flag++; //设置标志变量为重复
                }
            }
        }
        if(flag>1){//除首尾点外存在重复的点
            bool = true;//存在自相交
        }

        return bool;
    }

    private double GLOBAL_THRESH = 1E-6;
    //校验矢量面是否在存在两两重叠或相交（或单要素自相交）
    public String checkIsPolygonGeometrysIntersect(List<Geometry> multiPolygonGeometryList) {
        String resultStr = "校验成功";
        Geometry geometry1 = null;
        Geometry geometry2 = null;
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> polygonList = null;
        if(multiPolygonGeometryList!=null && multiPolygonGeometryList.size()>0) {
            for (int i = 0; i < multiPolygonGeometryList.size(); i++) {
                geometry1 = multiPolygonGeometryList.get(i);
                //Geometry geometry1IntersectGeometry1 = geometry1.intersection(geometry1);
                //判断是否存在两两重叠或相交
                for(int j=i+1;j<multiPolygonGeometryList.size();j++){
                    geometry2 = multiPolygonGeometryList.get(j);
                    //自相交
                    //Geometry geometry2IntersectGeometry2 = geometry2.intersection(geometry2);
                    //Geometry geometry1IntersectGeometry2 = geometry1IntersectGeometry1.intersection(geometry2IntersectGeometry2);
                    //double area = geometry1IntersectGeometry2.getArea();
                    //两两相交
                    Geometry geometry1IntersectGeometry2 = geometry1.intersection(geometry2);
                    double area = geometry1IntersectGeometry2.getArea();
                    if(area >= GLOBAL_THRESH){
                        resultStr = "isPolygonsIntersect";
                        String temp = "存在两两重叠或相交";
                        //temp += "，面："+geometry1.toString();
                        //temp += "相交于面："+geometry2.toString();
                        temp += "，相交面积："+area;
                        System.out.println(temp);
                        break;
                    }
                }
                if(resultStr!="校验成功"){
                    break;
                }
            }
        }

        return resultStr;
    }

    //校验矢量面数据是否在省市县所在区域边界内
    public boolean newCheckPointIsInDistrict(List<com.css.fxfzypg.modules.spatialData.repository.entity.Point[]> boundaries,List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> polygonList) {
        com.css.fxfzypg.modules.spatialData.repository.entity.Point point = null;
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Point> pointArray = null;
        com.css.fxfzypg.modules.spatialData.repository.entity.Point[] boundary = null;
        com.css.fxfzypg.modules.spatialData.repository.entity.Polygon polygon = null;

        if(boundaries!=null && boundaries.size()>0 && polygonList!=null && polygonList.size()>0){
            for(int i=0;i<polygonList.size();i++){
                boolean bool = false;
                polygon = polygonList.get(i);
                pointArray = polygon.points;
                if(pointArray!=null && pointArray.size()>0){
                    for(int j=0;j<pointArray.size();j++){
                        point = pointArray.get(j);
                        bool = false;
                        double minDis = Double.MAX_VALUE;
                        for (int k = 0; k < boundaries.size(); k++) {
                            boundary = boundaries.get(k);
                            if (AreaBoundaryUtil.isPointInPolygon(point, boundary)){
                                bool = true;
                                break;
                            } else {//判断容差距离
                                //double minDis = Double.MAX_VALUE;
                                for (int n = 0; n < boundary.length - 1; n++) {
                                    com.css.fxfzypg.modules.spatialData.repository.entity.Point p1 = boundary[n], p2 = boundary[n + 1];
                                    double d = AreaBoundaryUtil.pointToLine(p1.x, p1.y, p2.x, p2.y, point.x, point.y);
                                    if (minDis > d) minDis = d;
                                }
                                if (minDis < GLOBAL_THRESH) {
                                    bool = true;
                                    break;
                                }
                            }
                        }
                        if (bool == false){
                            String temp = "矢量面上的点："+point;
                            temp+="--------不在行政区划范围内----minDis:"+minDis;
                            System.out.println(temp);
                            return false;
                        }
                    }
                }
            }
        }else{
            System.out.println("无行政区划范围----");
            return false;
        }

        return true;
    }

    //校验点数据是否在省市县所在区域边界内
    public boolean newCheckPointIsInDistrictBoundary(List<com.css.fxfzypg.modules.spatialData.repository.entity.Point[]> boundaries,String lonStr, String latStr) {
        com.css.fxfzypg.modules.spatialData.repository.entity.Point point = new com.css.fxfzypg.modules.spatialData.repository.entity.Point(Double.parseDouble(lonStr), Double.parseDouble(latStr));
        com.css.fxfzypg.modules.spatialData.repository.entity.Point[] boundary = null;
        boolean bool = false;
        if(boundaries!=null && boundaries.size()>0){
            for (int k = 0; k < boundaries.size(); k++) {
                boundary = boundaries.get(k);
                if (AreaBoundaryUtil.isPointInPolygon(point, boundary)){
                    bool = true;
                    break;
                } else {//判断容差距离
                    double minDis = Double.MAX_VALUE;
                    for (int n = 0; n < boundary.length - 1; n++) {
                        com.css.fxfzypg.modules.spatialData.repository.entity.Point p1 = boundary[n], p2 = boundary[n + 1];
                        double d = AreaBoundaryUtil.pointToLine(p1.x, p1.y, p2.x, p2.y, point.x, point.y);
                        if (minDis > d) minDis = d;
                    }
                    if (minDis < GLOBAL_THRESH) {
                        bool = true;
                        break;
                    }
                }
            }
            if (bool == false){
                String temp = "点："+point+"--------不在行政区划范围内----";
                System.out.println(temp);
                return false;
            }
        }else{
            System.out.println("无行政区划范围----");
            return false;
        }

        return true;
    }

    private String strWKTMercator = "PROJCS[\"CGCS2000_GK_Zone_20\",GEOGCS[\"GCS_China_Geodetic_Coordinate_System_2000\",DATUM[\"D_China_2000\",SPHEROID[\"CGCS2000\",6378137.0,298.257222101]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Gauss_Kruger\"],PARAMETER[\"False_Easting\",20500000.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",117.0],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]";

    public void setStrWKTMercator(String wKTMercator){
        strWKTMercator = wKTMercator;
    }

    public String wkt2lonLat(String wktPolygon){
        Geometry geomtry = null;
        try {
            GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
            WKTReader reader = new WKTReader(geometryFactory);
            geomtry = reader.read(wktPolygon);
            geomtry = webMercator2lonLat(geomtry);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (geomtry != null)
            return geomtry.toString();
        else return null;
    }

    public Geometry webMercator2lonLat(Geometry geom){
        try{
            CoordinateReferenceSystem sourceTarget = CRS.parseWKT(strWKTMercator);
            CoordinateReferenceSystem crsTarget = CRS.decode("EPSG:4490");
            MathTransform transform = CRS.findMathTransform(sourceTarget, crsTarget, true);
            //MathTransform transform = CRS.findMathTransform(sourceTarget, DefaultGeographicCRS.WGS84, true);
            return JTS.transform(geom, transform);
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //判断字符串是否为整数或者小数（大于等于0）
    public static boolean isNumericFloat(String str){
        Pattern pattern = Pattern.compile("[0-9]*\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        float temp = Float.parseFloat(str);
        if(temp>=0){
            return true;
        }else{
            return false;
        }
    }

    //判断字符串是否为整数
    public static boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    //校验省市区县名称是否匹配
    public Boolean checkProvinceCityCounty(String province,String city,String county){
        Boolean bool = false;
        try {
            //判断省市县的名称是否符合规范
            String divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(province, "utf-8"),
                    URLEncoder.encode(city, "utf-8"),
                    URLEncoder.encode(county, "utf-8"));
            if (!PlatformObjectUtils.isEmpty(divisionIds)) {
                int length = divisionIds.split("_").length;
                if(length==3){
                    bool = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bool;
    }
}
